﻿using System;
using UnityEngine;

// 飞行过程中，摧毁
public class DestroyWhenFly
{
    private Action<GameObject> _hitBolckCallback;
    private Action<Enemy> _hitEnemyCallback;

    Transform _target;

    TimerMgr.Timer _timer;
    public void Init(Transform target, Action<GameObject> hitBolckCallback, Action<Enemy> hitEnemyCallback)
    {
        _target = target;
        _hitBolckCallback = hitBolckCallback;
        _hitEnemyCallback = hitEnemyCallback;

        _timer = TimerMgr.Instance.CreateTimer(0, -1, checkAndDestroy);
        _timer.Start();
    }

    private void checkAndDestroy()
    {
        var allCollider = Physics2D.OverlapAreaAll(
            new Vector2(_target.transform.position.x - 1, _target.transform.position.y +1),
            new Vector2(_target.transform.position.x + 1, _target.transform.position.y - 10), 1 << LayerMask.NameToLayer("Block") | 1 << LayerMask.NameToLayer("Enemy"));

        foreach (var other in allCollider)
        {
            // 阻挡做处理
            if (other.gameObject.layer == LayerMask.NameToLayer("Block"))
            {
                if (_hitBolckCallback != null) { _hitBolckCallback(other.gameObject); }
                return;
            }

            if (other.gameObject.layer == LayerMask.NameToLayer("Enemy"))
            {
                var enemy = other.GetComponent<Enemy>();
                if (enemy != null)
                {
                    if (_hitEnemyCallback != null) { _hitEnemyCallback(enemy); }
                }
                return;
            }
        }

    }

    internal void Release()
    {
        _timer.Stop();
    }
}